/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-05-12 20:53:15
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-05-12 22:12:13
 * @FilePath: /lesson40/1.sem_cp/Ringqueue.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include <vector>
#include <semaphore.h>

using namespace std;

const static int defaultnum = 5;

template <class T>
class Ringqueue
{
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t &sem)
    {
        sem_post(&sem);
    }
    void lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void unlock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    Ringqueue(int cap = defaultnum)
        : ringqueue_(cap), cap_(cap), c_step_(0), p_step_(0)
    {
        sem_init(&cdata_sem_, 0, 0);
        sem_init(&pspace_sem_, 0, cap_);

        pthread_mutex_init(&c_mutex_, nullptr);
        pthread_mutex_init(&p_mutex_, nullptr);
    }
    void Push(const T &in)
    {
        P(pspace_sem_);
        lock(p_mutex_);
        ringqueue_[p_step_++] = in;
        p_step_ %= cap_;
        unlock(p_mutex_);
        V(cdata_sem_);
    }
    void Pop(T *out)
    {
        P(cdata_sem_);
        lock(c_mutex_);
        *out = ringqueue_[c_step_++];
        c_step_ %= cap_;
        unlock(c_mutex_);
        V(pspace_sem_);
    }

    ~Ringqueue()
    {
        sem_destroy(&cdata_sem_);
        sem_destroy(&pspace_sem_);

        pthread_mutex_destroy(&c_mutex_);
        pthread_mutex_destroy(&p_mutex_);
    }

private:
    vector<T> ringqueue_;
    int cap_;

    int c_step_; // 消费者下标
    int p_step_; // 生产者下标

    sem_t cdata_sem_;  // 数据资源
    sem_t pspace_sem_; // 空间资源

    pthread_mutex_t c_mutex_;
    pthread_mutex_t p_mutex_;
};